<template>
  <el-dialog :title="'换房'" :close-on-click-modal="false" :visible.sync="visible" :append-to-body="true">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="操作" name="first"></el-tab-pane>
      <el-tab-pane label="换房记录" name="second"></el-tab-pane>
    </el-tabs>
    <el-form :model="dataForm" v-show="activeName == 'first'" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
      label-width="80px">
      <el-form-item label="原房间" prop="remarks">
        <span style="margin: 0px 5px 0px 0px;">{{ item.roomSign }}{{ item.roomNum }}</span>
        <div>
          房价：
          {{ prices[today] }}
          /
          {{ oPrice1 }}
          <el-popover placement="right" width="350" trigger="hover" :disabled="prices.dateList.length==0">
            <el-form label-width="100px" :inline="true" style="max-height: 300px !important;overflow-y: auto;">
              <el-form-item v-for="(item, index) in prices.dateList" :key="index" :label="dateList[index] + '：'">
                <span>{{item[dateList[index]]}}</span>
              </el-form-item>
            </el-form>
            <span slot="reference">
              <i class="el-icon-view" style="cursor: pointer;"></i>
            </span>
          </el-popover>
        </div>

      </el-form-item>
      <el-form-item label="新房间" prop="changeRoomid">
        <span>{{ selectItem.roomSign }}{{ selectItem.roomNum }}</span>
        <a type="text" style="cursor: pointer;margin: 0px 5px;" @click="selectRoom">选择</a>
        <div>
          房价：
          {{ dataForm.prices[today] }}
          /
          {{ oPrice2 }}
          <el-popover placement="right" width="350" trigger="hover" :disabled="dataForm.prices.dateList.length==0">
            <el-form label-width="100px" :inline="true" style="max-height: 300px !important;overflow-y: auto;">
              <el-form-item v-for="(item, index) in dataForm.prices.dateList" :key="index" :label="dateList[index]">
                <el-input :readonly="item.readonly" @change="changeTotalPrice2(dataForm.prices.dateList)" style="100px"
                  size="small" v-model="item[dateList[index]]" placeholder="金额"></el-input>
              </el-form-item>
            </el-form>
            <span slot="reference">
              <i class="el-icon-edit" style="cursor: pointer;"></i>
            </span>
          </el-popover>
        </div>

      </el-form-item>
      <el-form-item label="原因" prop="remarks">
        <el-input v-model="dataForm.remarks" placeholder="原因" type="textarea"></el-input>
      </el-form-item>
    </el-form>
    <span v-show="activeName == 'first'" slot="footer" class="dialog-footer">
      <el-checkbox v-model="huanfangCheck" style="margin-right: 10px;">打印换房单</el-checkbox>
      <el-button @click="visible = false">{{$t('Common.Cancel')}}</el-button>
      <el-button type="primary" @click="dataFormSubmit()">{{ $t('Common.Confirm') }}</el-button>
    </span>

    <changerecord @pringing="pringingData" v-show="activeName == 'second'" ref="changerecord"></changerecord>

    <floorroomselect v-if="floorroomselectVisible" ref="floorroomselect" @refreshData="selectRoomItem"></floorroomselect>

    <hf58 v-show="false" id="hf58" ref="hf58" :note="this.printconfig.note"></hf58>
    <hf80 v-show="false" id="hf80" ref="hf80" :note="this.printconfig.note"></hf80>
    <hfA5 v-show="false" id="hfA5" ref="hfA5" :note="this.printconfig.note"></hfA5>

  </el-dialog>
</template>

<script>
  import moment from 'moment';
  import floorroomselect from './floorroomselect';
  import changerecord from './changeroom/changerecord';

  import hf58 from '../../../common/printtemplate/huanfang_58mm';
  import hf80 from '../../../common/printtemplate/huanfang_80mm';
  import hfA5 from '../../../common/printtemplate/huanfang_A5';
  import {
    getLodop
  } from '../../../../utils/lodop';
  export default {
    data() {
      return {
        activeName: 'first',
        today: moment().format('YYYY-MM-DD'),
        huanfangCheck: false,
        visible: false,
        floorroomselectVisible: false,
        item: {},
        dateList: [],
        oPrice1: 0,
        oPrice2: 0,
        printconfig: {
          note: '',
        },
        selectItem: {

        },
        prices: {
          dateList: []
        },
        dataForm: {
          changeRoomid: '',
          remarks: '',
          prices: {
            dateList: []
          }
        },
        totlMoney: 0,
        totlMoney2: 0,
        dataRule: {
          sellerId: [{
            required: true,
            message: '商家不能为空',
            trigger: 'blur'
          }],
          changeRoomid: [{
            required: true,
            message: '请选择换房房间',
            trigger: 'blur'
          }],
        }
      };
    },
    components: {
      floorroomselect,
      changerecord,
      hf58,
      hf80,
      hfA5
    },
    methods: {
      handleClick(tab, event) {
        if (tab.index == 1) {
          this.$refs.changerecord.init(this.item.id);
        }
      },
      loadPrintConfig() {
        this.$http({
          url: this.$http.adornUrl(`/hotel/thotelprinttemplate/info/6`),
          method: 'get'
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.printconfig = data.tHotelPrintTemplate;
          } else {
            this.$message.error(data.msg);
          }
        });
      },
      printHuanFang() {
        this.$nextTick(() => {
          setTimeout(() => {
            LODOP = getLodop();
            if (!LODOP) {
              this.$alert(
                `<br><font color='#FF00FF'>CLodop云打印服务(localhost本地)未安装启动!点击这里<a href='http://www.lodop.net/download/CLodop_Setup_for_Win32NT_4.088Extend.zip' download target='_self'>执行安装</a>,安装后请刷新页面。</font>`,
                '安装', {
                  confirmButtonText: '确定',
                  dangerouslyUseHTMLString: true
                }
              );
              return;
            }

            //样式
            var strStyleCSS =
              " <link href='https://ebooking.qlan99.com/css/print.css' type='text/css' rel='stylesheet'> ";

            var olstyle1 = '<!DOCTYPE html><html lang="zh-CN"><head>' + strStyleCSS + '</head>' + ' <style> ' +
              'div{border:0!important}' + '</style>';
            var body = '';
            if (this.printconfig.specs === '58mm') {
              var olstyle2 = '<style> .print-wrap-normal{width:' + (58 + parseInt(this.printconfig.printContentOffset)) +
                'mm  !important}</style>';
              body = olstyle1 + olstyle2 + '<body>' + this.$refs.hf58.$refs.hf58.innerHTML + '</body>';
              LODOP.SET_PRINT_PAGESIZE(0, 580, 3000, ''); //设定纸张大小
            }
            if (this.printconfig.specs === '80mm') {
              var olstyle2 = '<style> .print-wrap-normal{width:' + (80 + parseInt(this.printconfig.printContentOffset)) +
                'mm  !important}</style>';
              body = olstyle1 + olstyle2 + '<body>' + this.$refs.hf80.$refs.hf80.innerHTML + '</body>';
              LODOP.SET_PRINT_PAGESIZE(0, 800, 2500, ''); //设定纸张大小
            }
            if (this.printconfig.specs === 'A5') {
              var olstyle2 = '<style> .print-wrap-normal{width:' + (210 + parseInt(this.printconfig.printContentOffset)) +
                'mm  !important}</style>';
              body = olstyle1 + olstyle2 + '<body>' + this.$refs.hfA5.$refs.hfA5.innerHTML + '</body>';
              LODOP.SET_PRINT_PAGESIZE(0, 2100, 2000, ''); //设定纸张大小
            }
            body += '</html>';
            LODOP.ADD_PRINT_HTM(0, 0, 1000, 2000, body); //增加超文本项

            LODOP.SET_PRINT_MODE('PRINT_PAGE_PERCENT', '100%'); //设置缩放
            // LODOP.PRINT_INIT('订单') //打印初始化
            LODOP.SET_PRINT_STYLE('FontSize', 12); //设置对象风格
            LODOP.SET_PRINT_STYLE('Bold', 1); ////设置对象风格
            LODOP.SET_PREVIEW_WINDOW(0, 0, 0, 0, 0, ''); //设置窗口
            LODOP.SET_PRINT_COPIES(this.printconfig.printSum);

            LODOP.SET_LICENSES("", "4B44F795076C8F14211A5ED0A5339305DAB", "23580B189D96F33252722697A57AC00506B",
              "");

            if (this.printconfig.preview) {
              if (LODOP.SET_PRINTER_INDEXA(this.printconfig.defaultPrint)) {
                LODOP.SET_PRINTER_INDEXA(this.printconfig.defaultPrint);
                LODOP.PRINT();
                // LODOP.PRINT_DESIGN();
              } else {
                LODOP.SET_PRINTER_INDEXA(0);
                LODOP.PRINT();
                // LODOP.PRINT_DESIGN();
              }
            } else {
              if (LODOP.SET_PRINTER_INDEXA(this.printconfig.defaultPrint)) {
                LODOP.SET_PRINTER_INDEXA(this.printconfig.defaultPrint);
                LODOP.PREVIEW();
              } else {
                LODOP.SET_PRINTER_INDEXA(0);
                LODOP.PREVIEW();
                // LODOP.PRINT_DESIGN();
              }
            }
          }, 100)

        });
      },
      //加载日期
      getdateList() {
        this.dateList = [];
        //计算时间差
        var startDate = moment(this.item.typeStartTime);
        var stopDate = moment(this.item.typeStopTime);
        const date = stopDate.diff(startDate, 'day');
        //加载日期
        for (var i = 0; i < 90; i++) {
          this.dateList.push(
            moment(this.item.typeStartTime)
            .add(i, 'days')
            .format('YYYY-MM-DD')
          );
        }
      },
      //查询门市价
      searchOPrice(roomId) {
        this.$http({
          url: this.$http.adornUrl(`/hotel/hotelroomprice/searchOPrice`),
          method: 'get',
          params: this.$http.adornParams({
            roomId: roomId,
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            if (data.data.roomId == this.selectItem.roomId) {
              this.oPrice2 = data.data.money;
            }
            if (data.data.roomId == this.item.roomId) {
              this.oPrice1 = data.data.money;
            }
          } else {
            this.$message.error(data.msg);
          }
        });
      },
      //计算总金额
      changeTotalPrice(list) {
        this.totlMoney = 0;
        list.forEach((item, index) => {
          this.totlMoney += parseFloat(item[this.dateList[index]]);
        });
      },
      changeTotalPrice2(list) {
        this.totlMoney2 = 0;
        this.dataForm.prices[this.today] = 0;
        list.forEach((item, index) => {
          this.totlMoney2 += parseFloat(item[this.dateList[index]]);
          this.dataForm.prices[this.today] += parseFloat(item[this.dateList[index]]);
        });
      },
      selectRoomItem(item) {
        console.log(item)
        this.selectItem = item
        this.dataForm.changeRoomid = item.id
        this.searchOPrice(item.roomId)
        //查询该房间价格
        this.$http({
          url: this.$http.adornUrl(`/hotel/hotelroomprice/list3`),
          method: 'get',
          params: this.$http.adornParams({
            startDate: moment(this.item.typeStartTime).format('YYYY-MM-DD'),
            endDate: moment(this.item.typeStopTime).format('YYYY-MM-DD'),
            ids: item.roomId
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            data.data.dataList.forEach((item, index) => {
              if (item.roomId == this.selectItem.roomId) {
                let _obj = JSON.stringify(item),
                  objClone = JSON.parse(_obj);
                this.dataForm.prices = objClone;
                console.log(item);
              }
            });
            this.changeTotalPrice2(this.dataForm.prices.dateList)
            this.dataForm.prices.dateList.forEach((item, index) => {
              var startDate = moment(this.dataForm.prices.dateList[index]);
              var stopDate = moment();
              var zuoDay = moment().add(-1, "days").format('YYYY-MM-DD')
              const date = stopDate.diff(startDate, 'day');
              item.readonly = false
              console.log(date)
              console.log(startDate == stopDate)
              console.log(startDate == zuoDay)
              console.log(startDate)
              console.log(zuoDay)
              if (date < 0 || startDate == zuoDay) {
                item.readonly = true
              }
            })
          } else {
            this.$message.error(data.msg);
          }
        });
      },
      init(item) {

        Object.assign(this.$data, this.$options.data())
        this.$nextTick(() => {
          if (this.$cookie.get('huanfangCheck') != null) {
            if (this.$cookie.get('huanfangCheck') == 1) {
              this.huanfangCheck = true
            } else {
              this.huanfangCheck = false
            }
          }
          this.loadPrintConfig();
          this.visible = true;
          this.item = item;
          this.searchOPrice(item.roomId)
          this.getdateList();
          this.prices = JSON.parse(item.prices);
          console.log("item.prices", item.prices)
          console.log("this.prices", this.prices)
          this.changeTotalPrice(this.prices.dateList)
          this.changeTotalPrice2(this.dataForm.prices.dateList)
        })
      },
      selectRoom() {
        this.floorroomselectVisible = true;
        this.$nextTick(() => {
          this.$refs.floorroomselect.init([this.selectItem]);
        });
      },
      pringingData(pdata) {
        this.$refs.hf58.setData(pdata);
        this.$refs.hf80.setData(pdata);
        this.$refs.hfA5.setData(pdata);
        this.$message({
          message: this.$t('Common.OperationSuccessful'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.printHuanFang();
          }
        });
      },
      //换房
      dataFormSubmit() {
        console.log("item", this.item)
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.huanfangCheck) {
              this.$cookie.set('huanfangCheck', 1)
            } else {
              this.$cookie.set('huanfangCheck', 2)
            }
            this.$http({
              url: this.$http.adornUrl(`/hotel/thotelfloorroomcheckinpeople/change_room`),
              method: 'post',
              data: this.$http.adornData({
                roomId: this.item.id,
                changeRoomid: this.dataForm.changeRoomid,
                remarks: this.dataForm.remarks,
                peopleId: this.item.peopleId,
                state: this.huanfangCheck ? 1 : 2,
                dh: this.item.sisysno,
                price: JSON.stringify(this.dataForm.prices)
              })
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$nextTick(() => {
                  this.$emit('refreClosing');
                  this.$emit('refreshDataList')
                });
                this.visible = false

                if (this.huanfangCheck) {
                  var pdata = data.data
                  this.$refs.hf58.setData(pdata);
                  this.$refs.hf80.setData(pdata);
                  this.$refs.hfA5.setData(pdata);
                  console.log(pdata);
                }
                this.$message({
                  message: this.$t('Common.OperationSuccessful'),
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    if (this.huanfangCheck) {
                      this.printHuanFang();
                    }
                  }
                });
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  };
</script>

<style>
</style>
